package yl.hs.bmipfull.service.laboratory.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.laboratory.IProductCateDao;
import yl.hs.bmipfull.daos.laboratory.IProductInfoDao;
import yl.hs.bmipfull.daos.production.IFinishProductInventoryDao;
import yl.hs.bmipfull.daos.production.IProductionPackageDao;
import yl.hs.bmipfull.pojo.laboratory.ProductInfoEntity;
import yl.hs.bmipfull.service.laboratory.IProductInfoService;
import yl.hs.bmipfull.service.salemanage.ISaleContractProductsService;
import yl.hs.bmipfull.utils.DataState;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.SearchFilterEngine;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 作用:  产品信息表服务层接口实现<br/>
 * 创建时间: 2021年05月22日 14时48分28秒 <br/>
 *
 * @author 吴高丰
 */
@Service
public class ProductInfoServiceImpl extends LaboratoryBaseService implements IProductInfoService {

    @Autowired
    IProductInfoDao dao;
    @Autowired
    ISaleContractProductsService productsService;
    @Autowired
    IProductCateDao cateDao;
    @Autowired
    IProductionPackageDao packageDao;
    @Autowired
    IFinishProductInventoryDao inventoryDao;
    @Override
    public List<ProductInfoEntity> queryList(PageQuery pageQuery) throws Exception {
        pageQuery.checkSortSides(ProductInfoEntity.class);
        pageQuery.getQuery().put("unitSNArray", getCompanySNList());
        var result = dao.queryList(pageQuery.getQuery());
        var weiht = result.stream().map(ProductInfoEntity::getDefectiveWeight).reduce(BigDecimal::add);
        var quantity = result.stream().map(ProductInfoEntity::getDefectiveQuantity).reduce(BigDecimal::add);
        result.forEach(s->{
            s.setTotildefectiveWeight(weiht.get());
            s.setTotildefectiveQuantity(quantity.get());
            var dd = cateDao.findBySN(s.getProductCateSN());
            s.setProductCode(dd.getCateName());
        });
        return result;
    }

    @Override
    public PageResult<ProductInfoEntity> queryPage(PageQuery pageQuery, int rowNum, int page) throws Exception {
        pageQuery.checkSortSides(ProductInfoEntity.class);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        PageResult<ProductInfoEntity> result = new PageResult(rowNum);
        pageQuery.getQuery().put("unitSNArray", getCompanySNList());
        var filters = SearchFilterEngine.generateQueryList(pageQuery.getFilters(),ProductInfoEntity.class);
        result.setRecords(dao.queryCountByCondition(pageQuery.getQuery(),filters));
        result.setPage(page);
        result.setData(dao.queryPage(pageQuery.getQuery(),filters));
        return result;
    }

    @Override
    public List<ProductInfoEntity> queryByTags(String tags) {
        return dao.queryByTags(tags);
    }


    @Override
    public ProductInfoEntity findBySn(String sn) {
        return dao.findBySN(sn);
    }

    @Override
    @Transactional
    public Integer saveProductInfo(Map<String, Object> model, String sn) throws Exception {
        Integer result = 0;
        ProductInfoEntity entity;
        if (Tl.isEmpty(sn)) {
            //执行保存
            entity = new ProductInfoEntity();
            var changeLog = Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            entity.setSn(queryNewSN(ProductInfoEntity.class));

            entity.setOrganizationCode(getDepartSN());
            result = dao.insertNew(entity);
            if (result > 0) {
                writeLog(ActionType.CREATE, entity.getSn(), "插入产品信息表信息", Tl.toJson(entity), ProductInfoEntity.class);
            }

        } else {
            //执行修改
            entity = findBySn(sn);
            var backJson = entity.toJson();
            var changeLog = Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            entity.setOrganizationCode(getDepartSN());
            result = dao.update(entity);
            if (result > 0) {
                writeLog(ActionType.UPDATE, sn, changeLog, backJson, ProductInfoEntity.class);
            }
        }
        if (result > 0) {
            saveGS(
                    entity.getSn(),
                    entity.getProductName(),
                    String.join(",",
                            entity.getProductName(),
                            entity.getProductSpec(),
                            entity.getProductCode()
                    ),
                    entity,
                    HsApp.getCurrent() != null ? HsApp.getCurrent().getUserSN() : null,
                    entity.getOrganizationCode()
            );
        }
        return result;
    }

    @Override
    public Integer delete(String[] sn) {
        var result = dao.changeStateBySn(sn, DataState.DELETED.code);
        var entity = dao.findBySN(sn[0]);
        if(entity!=null){
           var inven = inventoryDao.quantityByProductSN(entity.getSn());
           if(inven.size()>0){
               return -1;
           }
        }
        if (result > 0) {
            writeLog(ActionType.DELETE, sn, ProductInfoEntity.class);
            deleteGs(sn);
            packageDao.deleteByProductSN(Arrays.stream(sn).toList());
        }
        return result;
    }

    @Override
    public List<ProductInfoEntity> queryByCateSn(String cateSn) {

        return dao.queryByCateSn(cateSn);
    }

    @Override
    public BigDecimal getDensity(String contractSn, String productSn) throws Exception {
        if (Tl.isEmpty(contractSn)) {
            ProductInfoEntity entity = findBySn(productSn);

            return entity != null ? entity.getDensity() : BigDecimal.valueOf(1);
        } else {
            PageQuery pageQuery = new PageQuery();
            pageQuery.getQuery().put("contractSN", contractSn);
            pageQuery.getQuery().put("productSN", productSn);

            var productsEntities = productsService.queryList(pageQuery);
            if (productsEntities.size() > 0) {
                return BigDecimal.valueOf((float) productsEntities.get(0).get("density")).setScale(2,2);
            } else {
                ProductInfoEntity entity = findBySn(productSn);
                return entity != null ? entity.getDensity() : BigDecimal.valueOf(1);
            }

        }

    }

    @Override
    public List<ProductInfoEntity> queryAll() {
        return dao.queryAll();
    }

    @Override
    public Integer changeStateBySN(String[] snList, short state) {
        int result=dao.changeStateBySn(snList,state);
        if (result > 0) {
            forWriteLog(snList,state);
        }
        return result;
    }
}